﻿using Blog1._0.Data;
using Blog1._0.Service;
using System;
using System.Web.Mvc;
using Until;
using System.Linq;


namespace Blog1._0.Controllers
{
    /// <summary>
    /// 【留言】控制器
    /// </summary>
    public class FeedbackController : Controller
    {
        FeedbackService service = new FeedbackService();
        /// <summary>
        /// 留言首页视图
        /// </summary>
        /// <returns></returns> 
        public ActionResult Index()
        {
            WebSiteInfo siteInfo = new WebSiteInfo();
            ViewBag.Site = siteInfo.GetWebSiteInfo();
            int Count = service.GetFeedList();
            ViewBag.Count = Count;
            int PageSize = 10;
            ViewBag.PageSize = PageSize;
            ViewBag.PageCount = (Count + PageSize - 1) / PageSize;
            return View();
        }

        /// <summary>
        /// 加载留言数据
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult LoadFeedback(int page, int pagesize)
        {
            string result = service.GetFlowFeedback(page, pagesize);
            return Content(result);
        }

        /// <summary>
        /// 提交评论
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="editorContent"></param>
        /// <param name="fromcity"></param>
        /// <param name="browserName"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public JsonResult AddFeedback(string openid,string email,string editorContent, string fromcity, string browserName)
        {
            var db = new Repository().Base();
            QQUserService services = new QQUserService();
            var userModel = services.GetQQUserInfo(openid).FirstOrDefault();
            if (userModel == null)
            {
                return Json(new AjaxResult { state = ResultType.error.ToString(), message = "非法提交，Openid不存在" });
            }
            if (!userModel.Status.Value)
            {
                return Json(new AjaxResult { state = ResultType.error.ToString(), message = "QQ用户已被锁定，无法留言" });
            }
            bool emails = services.InsertEmail(openid, email);//插入用户输入的email
            if (!emails)
            {
                return Json(new AjaxResult { state = ResultType.error.ToString(), message = "邮箱提交失败，请刷新重试" });

            }
            WebSiteInfo siteInfo = new WebSiteInfo();
            int maxFeedbackNum = Convert.ToInt32(siteInfo.GetWebSiteInfo().MaxFeedbackNum);//查询最大留言数量
            int todayFeedbackNum = service.GetTodayFeedbackNum(openid);//获取用户今日留言数量
            if (todayFeedbackNum >= maxFeedbackNum)//不能超过最大数量
            {
                //锁定QQ用户
                userModel.Status = false;
                db.Update(userModel);
                db.Commit();
                return Json(new AjaxResult { state = ResultType.error.ToString(), message = "留言提交失败，已超出每日最大提交数量" });
            }
            FeedbackModel model = new FeedbackModel()
            {
                SendId = userModel.Id,
                AcceptId = 0,
                Content = XSS.FilterXSS(editorContent),
                ParentId = 0,
                City = fromcity,
                Equip = browserName,
                CreateOn = DateTime.Now
            };
            bool result = service.CreateModel(model);
            if (result)
            {
                return Json(new AjaxResult { state = ResultType.success.ToString(), message = "留言提交成功" });
            }
            else
            {
                return Json(new AjaxResult { state = ResultType.error.ToString(), message = "留言提交失败" });
            }
        }

        /// <summary>
        /// 回复留言
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="remarkId"></param>
        /// <param name="targetUserId"></param>
        /// <param name="editorContent"></param>
        /// <param name="fromcity"></param>
        /// <param name="browserName"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public JsonResult ReplyFeedback(string openid, string remarkId, string targetUserId, string editorContent, string fromcity, string browserName)
        {
            var db = new Repository().Base();
            QQUserService services = new QQUserService();
            var userModel = services.GetQQUserInfo(openid).FirstOrDefault();//查询用户是否存在
            if (userModel == null)
            {
                return Json(new AjaxResult { state = ResultType.error.ToString(), message = "非法提交，Openid不存在" });
            }
            if (!userModel.Status.Value)
            {
                return Json(new AjaxResult { state = ResultType.error.ToString(), message = "QQ用户已被锁定，无法留言" });
            }
            WebSiteInfo siteInfo = new WebSiteInfo();
            int maxFeedbackNum = Convert.ToInt32(siteInfo.GetWebSiteInfo().MaxFeedbackNum);
            int todayFeedbackNum = service.GetTodayFeedbackNum(openid);
            if (todayFeedbackNum >= maxFeedbackNum)
            {
                //锁定QQ用户
                userModel.Status = false;
                db.Update(userModel);
                db.Commit();
                return Json(new AjaxResult { state = ResultType.error.ToString(), message = "留言提交失败，已超出每日最大提交数量" });
            }
            FeedbackModel model = new FeedbackModel()
            {
                SendId = userModel.Id,
                AcceptId = Convert.ToInt32(targetUserId),
                Content = XSS.FilterXSS(editorContent),
                ParentId = Convert.ToInt32(remarkId),
                City = fromcity,
                Equip = browserName,
                CreateOn = DateTime.Now
            };
            bool result = service.CreateModel(model);
            if (model.SendId != model.AcceptId)
            {
                //不相等则代表他人回复，找到被回复的人openid，查询到他的邮箱
                var BackEmail = services.GetEmails(model.AcceptId);
                var response = new EmailsService().SendActivateEmail(BackEmail);
                if (response.state.ToString() == "error")
                {
                    return Json(new AjaxResult { state = ResultType.error.ToString(), message = "邮件发送失败" });
                }
            }
            if (result)
            {
                return Json(new AjaxResult { state = ResultType.success.ToString(), message = "留言回复成功" });
            }
            else
            {
                return Json(new AjaxResult { state = ResultType.error.ToString(), message = "留言回复失败" });
            }
        }

        /// <summary>
        /// 查询邮箱
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>
        public JsonResult IsCheckEmail(string openid)
        {
            QQUserService services = new QQUserService();
            var userModel = services.GetQQUserInfo(openid).FirstOrDefault();//查询用户是否存在
            if (userModel.Email != "")
            {
                return Json(new AjaxResult { state = ResultType.success.ToString(), data = userModel.Email });
            }
            else
            {
                return Json(new AjaxResult { state = ResultType.error.ToString() });
            }
        }
    }
}